/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.johanwi.jsfproducts;

import edu.chl.johanwi.jpa.nbp.Exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Schtohan
 */
@ManagedBean
@SessionScoped
public class viewProductsControllerBean implements Serializable{

    private List<Product> productList = new ArrayList<Product>();
    private Product selected;
    
    /** Creates a new instance of viewProductsControllerBean */
    public viewProductsControllerBean() {
        productList = Database.getProductController().findEntities();
    }

    public List<Product> getProductList() {
        return productList;
    }

    public void setProductList(List<Product> productList) {
        this.productList = productList;
    }

    public Product getSelected() {
        return selected;
    }

    public void setSelected(Product selected) {
        this.selected = selected;
    }
       
    public String doEmpty(){
        
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "onEmptyCart";
        
    }

    public void removeProduct()
    {
        try
        {
            Database.getProductController().destroy(selected.getId());  
            productList.remove(selected);
            shoppingCart sc = (shoppingCart) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("shoppingCart");
            List<Product> pl = sc.getProductList();  
            List<Product> rl = new ArrayList<Product>();
            for(Product p : pl)
            {
                if(p.getId().equals(selected.getId())){
                    rl.add(p);
                }
            }
            pl.removeAll(rl);
            sc.setNumberOfProducts(pl.size());
            
        }
        catch(NonexistentEntityException e)
        {
            
        }
    }

}
